package com.woniuxy.shiro;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 马宇航
 * @Todo: JWT过滤器，拦截token信息
 * @DateTime: 22/02/23/0023 上午 11:04
 * @Component: 成都蜗牛学苑
 **/
public class JWTFilter extends BasicHttpAuthenticationFilter {
    /**
     * @Todo: 这里一般都是用于统一后台跨域解决！后端跨域的代码不能有多个，只能用一套方案！
     *      前端处理了后端就可以不写！
     * ChangeLog : 1. 创建 (22/02/23/0023 上午 11:05 [马宇航]);
     * @param request
     * @param response
     * @return boolean
    */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
    /**
     * @Todo: token认证入口，进行业务逻辑处理！和后续过滤器方法的调用
     * ChangeLog : 1. 创建 (22/02/23/0023 上午 11:08 [马宇航]);
     * @param request
     * @param response
     * @param mappedValue
     * @return boolean
    */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //检查认证请求 获取请求头中的token
        if (isLoginAttempt(request,response)){
            try {
                //执行登录 subject.login
                executeLogin(request,response);
            } catch (Exception e) {
                //如果请求头中没有token  跳转到401请求！让401controller返回前端一个请求
                response401(request,response);
                e.printStackTrace();
            }
        }else {
            //如果没有请求头的情况，我们直接返回401信息即可！
            response401(request,response);
        }
        return true;
    }
    /**
     * @Todo: 登录请求判断，尝试获取请求头中的token信息！
     * ChangeLog : 1. 创建 (22/02/23/0023 上午 11:10 [马宇航]);
     * @param request
     * @param response
     * @return boolean
    */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //从请求头中获取认证token信息
        String token = request1.getHeader("Authorization");
        return token!=null;
    }
    /**
     * @Todo: 最终执行登录的方法！
     * ChangeLog : 1. 创建 (22/02/23/0023 上午 11:14 [马宇航]);
     * @param request
     * @param response
     * @return boolean
    */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //从请求头中获取认证token信息
        String token = request1.getHeader("Authorization");
        getSubject(request,response).login(new MyJsonWebToken(token));
        return true;
    }
    //如果请求头没有token则跳转401请求controller
   private void response401(ServletRequest request, ServletResponse response){
       HttpServletRequest request1 = (HttpServletRequest) request;
       try {
           request1.getRequestDispatcher("/401").forward(request,response);
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ServletException e) {
           e.printStackTrace();
       }
   }
}
